import { Button, Tag, Space, Popconfirm, Tooltip, message } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, DeleteOutlined, EditOutlined, EyeOutlined, ThunderboltOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { system } from '@/forent-api/api';

// 定时任务状态映射
export const TaskStatusMap = {
  0: { text: '停用', color: 'default' },
  1: { text: '启用', color: 'success' }
};

// 任务类型映射
export const TaskTypeMap = {
  'api_call': { text: 'API调用', color: 'blue' },
  'database_cleanup': { text: '数据库清理', color: 'orange' },
  'data_sync': { text: '数据同步', color: 'purple' },
  'report_generate': { text: '报表生成', color: 'green' },
  'system_monitor': { text: '系统监控', color: 'red' },
  'custom': { text: 'Shell脚本', color: 'magenta' },
  'javascript': { text: 'JavaScript代码', color: 'gold' }
};

// 表格列定义
export const getTableColumns = (
  onEdit: (record: any) => void,
  onViewLogs: (record: any) => void,
  onRefresh: () => void
): ColumnsType<any> => [
  {
    title: '任务名称',
    dataIndex: 'task_name',
    key: 'task_name',
    width: 160,
    ellipsis: true,
  },
  {
    title: '任务编码',
    dataIndex: 'task_code',
    key: 'task_code',
    width: 100,
    ellipsis: true,
  },
  {
    title: '任务类型',
    dataIndex: 'task_type',
    key: 'task_type',
    width: 80,
    render: (type: string) => {
      const typeInfo = TaskTypeMap[type as keyof typeof TaskTypeMap];
      return (
        <Tag color={typeInfo?.color || 'default'}>
          {typeInfo?.text || type}
        </Tag>
      );
    },
  },
  {
    title: 'Cron表达式',
    dataIndex: 'cron_expression',
    key: 'cron_expression',
    width: 120,
    render: (cron: string) => (
      <Tooltip title={cron}>
        <code style={{ fontSize: '12px' }}>{cron}</code>
      </Tooltip>
    ),
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
    render: (status: number) => {
      const statusInfo = TaskStatusMap[status as keyof typeof TaskStatusMap];
      return (
        <Tag color={statusInfo.color}>
          {statusInfo.text}
        </Tag>
      );
    },
  },
  {
    title: '执行状态',
    dataIndex: 'isExecuting',
    key: 'isExecuting',
    width: 80,
    render: (isExecuting: boolean) => (
      <Tag color={isExecuting ? 'processing' : 'default'}>
        {isExecuting ? '执行中' : '空闲'}
      </Tag>
    ),
  },
  {
    title: '执行次数',
    dataIndex: 'run_count',
    key: 'run_count',
    width: 80,
    render: (count: number) => (
      <span style={{ color: '#1890ff' }}>{count}</span>
    ),
  },
  {
    title: '最后执行时间',
    dataIndex: 'last_run_time',
    key: 'last_run_time',
    width: 130,
    render: (time: string) => (
      <span style={{ fontSize: '12px' }}>
        {time || '未执行'}
      </span>
    ),
  },
  {
    title: '下次执行时间',
    dataIndex: 'next_run_time',
    key: 'next_run_time',
    width: 130,
    render: (time: string) => (
      <span style={{ fontSize: '12px' }}>
        {time || '未设置'}
      </span>
    ),
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    width: 150,
    render: (time: string) => (
      <span style={{ fontSize: '12px' }}>{time}</span>
    ),
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 220,
    render: (_, record) => (
      <Space size="small">
        <Tooltip title={record.isExecuting ? "任务执行中，无法编辑" : "编辑"}>
          <Button
            type="text" 
            size="small"
            icon={<EditOutlined />}
            onClick={() => {
              if (record.isExecuting) {
                message.warning('任务正在执行中，请等待执行完成后再编辑');
                return;
              }
              onEdit(record);
            }}
            disabled={record.isExecuting}
          />
        </Tooltip>
        
        <Tooltip title={record.status === 1 ? '停用' : '启用'}>
          <Popconfirm
            title={`确定要${record.status === 1 ? '停用' : '启用'}此任务吗？`}
            onConfirm={() => handleToggleTask(record, onRefresh)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={record.status === 1 ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              style={{ color: record.status === 1 ? '#ff4d4f' : '#52c41a' }}
            />
          </Popconfirm>
        </Tooltip>

        <Tooltip title="手动执行">
          <Popconfirm
            title="确定要立即执行此任务吗？"
            onConfirm={() => handleExecuteTask(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={<ThunderboltOutlined />}
              style={{ color: '#1890ff' }}
            />
          </Popconfirm>
        </Tooltip>

        <Tooltip title="查看日志">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onViewLogs(record)}
          />
        </Tooltip>

        <Tooltip title={record.isExecuting ? "任务执行中，无法删除" : "删除"}>
          <Popconfirm
            title="确定要删除此任务吗？"
            onConfirm={() => handleDeleteTask(record, onRefresh)}
            okText="确定"
            cancelText="取消"
            disabled={record.isExecuting}
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              danger
              disabled={record.isExecuting}
              onClick={(e) => {
                if (record.isExecuting) {
                  e.preventDefault();
                  message.warning('任务正在执行中，请等待执行完成后再删除');
                }
              }}
            />
          </Popconfirm>
        </Tooltip>
      </Space>
    ),
  },
];

// 启停任务
const handleToggleTask = async (record: any, onRefresh: () => void) => {
  try {
    const result = await system.toggleTimerTask({
      id: record.id,
      status: record.status === 1 ? 0 : 1
    });
    
    if (result.code === 200) {
      message.success(result.msg || '操作成功');
      onRefresh();
    } else {
      message.error(result.msg || '操作失败');
    }
  } catch (error) {
    message.error('操作失败');
  }
};

// 删除任务
const handleDeleteTask = async (record: any, onRefresh: () => void) => {
  try {
    const result = await system.deleteTimerTask({ id: record.id });
    
    if (result.code === 200) {
      message.success('删除成功');
      onRefresh();
    } else {
      message.error(result.msg || '删除失败');
    }
  } catch (error) {
    message.error('删除失败');
  }
};

// 手动执行任务
const handleExecuteTask = async (record: any) => {
  try {
    const result = await system.executeTimerTask({ id: record.id });
    
    if (result.code === 200) {
      message.success('任务执行完成');
    } else {
      message.error(result.msg || '执行失败');
    }
  } catch (error) {
    message.error('执行失败');
  }
};

// 表单验证规则
export const formRules = {
  task_name: [
    { required: true, message: '请输入任务名称' },
    { max: 100, message: '任务名称不能超过100个字符' }
  ],
  task_code: [
    { required: true, message: '请输入任务编码' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '任务编码只能包含字母、数字、下划线和横杠' },
    { max: 50, message: '任务编码不能超过50个字符' }
  ],
  cron_expression: [
    { required: true, message: '请输入Cron表达式' },
    { 
      pattern: /^(\*|[0-5]?\d|\*\/\d+) (\*|[0-5]?\d|\*\/\d+) (\*|[01]?\d|2[0-3]|\*\/\d+) (\*|[01]?\d|2[0-9]|3[01]|\*\/\d+) (\*|[01]?\d|1[0-2]|\*\/\d+)$/, 
      message: '请输入正确的Cron表达式格式' 
    }
  ],
  task_type: [
    { required: true, message: '请选择任务类型' }
  ],
  description: [
    { max: 500, message: '任务描述不能超过500个字符' }
  ]
};

// 获取任务配置验证规则
export const getTaskConfigRules = (taskType: string) => {
  if (taskType === 'javascript') {
    return [
      { required: true, message: '请输入JavaScript代码' },
      {
        validator: (rule: any, value: string) => {
          if (!value || value.trim() === '') {
            return Promise.reject(new Error('JavaScript代码不能为空'));
          }
          if (value.trim().length < 5) {
            return Promise.reject(new Error('JavaScript代码至少需要5个字符'));
          }
          return Promise.resolve();
        }
      }
    ];
  } else {
    return [
      {
        validator: (rule: any, value: string) => {
          if (!value || value.trim() === '') {
            return Promise.resolve(); // 允许为空
          }
          try {
            JSON.parse(value);
            return Promise.resolve();
          } catch (error) {
            return Promise.reject(new Error('请输入有效的JSON格式'));
          }
        }
      }
    ];
  }
};

// 日志表格列定义
export const getLogTableColumns = (): ColumnsType<any> => [
  {
    title: '执行时间',
    dataIndex: 'execute_time',
    key: 'execute_time',
    width: 150,
    render: (time: string) => (
      <span style={{ fontSize: '12px' }}>{time}</span>
    ),
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    render: (status: number) => (
      <Tag color={status === 1 ? 'success' : 'error'}>
        {status === 1 ? '成功' : '失败'}
      </Tag>
    ),
  },
  {
    title: '耗时',
    dataIndex: 'cost_time',
    key: 'cost_time',
    width: 100,
    render: (time: number) => (
      <span style={{ color: '#1890ff' }}>{time}ms</span>
    ),
  },
  {
    title: '执行结果',
    dataIndex: 'result',
    key: 'result',
    ellipsis: true,
    render: (result: string) => {
      if (!result) return '-';
      try {
        const parsed = JSON.parse(result);
        return (
          <Tooltip title={<pre>{JSON.stringify(parsed, null, 2)}</pre>}>
            <span style={{ color: '#52c41a' }}>查看详情</span>
          </Tooltip>
        );
      } catch {
        return (
          <Tooltip title={result}>
            <span>{result.length > 50 ? result.substring(0, 50) + '...' : result}</span>
          </Tooltip>
        );
      }
    },
  },
  {
    title: '错误信息',
    dataIndex: 'error_msg',
    key: 'error_msg',
    ellipsis: true,
    render: (error: string) => {
      if (!error) return '-';
      return (
        <Tooltip title={error}>
          <span style={{ color: '#ff4d4f' }}>
            {error.length > 50 ? error.substring(0, 50) + '...' : error}
          </span>
        </Tooltip>
      );
    },
  },
];

// 常用Cron表达式
export const CommonCronExpressions = [
  { label: '每分钟', value: '* * * * *' },
  { label: '每5分钟', value: '*/5 * * * *' },
  { label: '每10分钟', value: '*/10 * * * *' },
  { label: '每15分钟', value: '*/15 * * * *' },
  { label: '每30分钟', value: '*/30 * * * *' },
  { label: '每小时', value: '0 * * * *' },
  { label: '每天0点', value: '0 0 * * *' },
  { label: '每天6点', value: '0 6 * * *' },
  { label: '每天12点', value: '0 12 * * *' },
  { label: '每天18点', value: '0 18 * * *' },
  { label: '每周一0点', value: '0 0 * * 1' },
  { label: '每月1号0点', value: '0 0 1 * *' },
];

// 任务配置示例模板
export const TaskConfigTemplates = {
  api_call: {
    name: 'API调用示例',
    config: {
      "url": "https://api.example.com/sync",
      "method": "POST",
      "headers": {
        "Authorization": "Bearer your_token_here",
        "Content-Type": "application/json"
      },
      "data": {
        "syncType": "incremental"
      },
      "timeout": 30000,
      "retries": 3
    }
  },
  custom: {
    name: 'Shell脚本示例',
    config: {
      "path": "/path/to/script.sh",
      "args": ["--option", "value"],
      "workingDir": "/data",
      "timeout": 60000
    }
  },
  javascript: {
    name: 'JavaScript代码示例',
    config: {
      "code": "console.log('测试定时任务'); console.log('当前时间:', new Date()); result = '执行成功';"
    }
  },
  system_monitor: {
    name: '系统监控示例',
    config: {
      "checkMemory": true,
      "checkDisk": true,
      "alertThreshold": 80
    }
  },
  database_cleanup: {
    name: '数据库清理示例',
    config: {
      "table": "sys_log",
      "days": 30,
      "batchSize": 1000
    }
  }
}; 